package com.chenyun.satoken.starter.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.jwt.exception.SaJwtException;
import com.chenyun.common.vo.AjaxResult;
import com.chenyun.common.vo.ResultCode;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常捕获类
 *
 * @author: Lonni
 * @date: 2022/8/12 0012 11:11
 */
@Order(100)
@RestControllerAdvice
public class SatokenExceptionHandler {
    @ResponseBody
    @ExceptionHandler(value = {NotLoginException.class,
            NotRoleException.class,
            NotPermissionException.class,
            SaJwtException.class
    })
    public AjaxResult handlerException(RuntimeException e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        e.printStackTrace();
        // 不同异常返回不同状态码
        if (e instanceof NotLoginException) {
            // 如果是未登录异常
            NotLoginException ee = (NotLoginException) e;
            return new AjaxResult(ResultCode.UNAUTHENTICATED.code(), ee.getLocalizedMessage(), false);
        } else if (e instanceof NotRoleException) {
            // 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            return new AjaxResult(ResultCode.UNAUTHORISE.code(), ee.getLocalizedMessage(), false);
        } else if (e instanceof NotPermissionException) {
            // 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            return new AjaxResult(ResultCode.UNAUTHORISE.code(), ee.getLocalizedMessage(), false);
        } else if (e instanceof SaJwtException) {
            return new AjaxResult(ResultCode.TOKEN_NOT_EXP);
        } else {
            return AjaxResult.FAIL(e.getMessage());
        }
    }


}
